package com.msb.strategy.filter.impl;

import com.msb.common.constart.CacheConstant;
import com.msb.common.constart.RabbitMQConstants;
import com.msb.common.model.StandardSubmit;
import com.msb.common.util.OperatorUtil;
import com.msb.strategy.feign.BeaconCacheClient;
import com.msb.strategy.filter.StrategyFilter;
import com.msb.strategy.util.MobilOperatorUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 号段补全：获取手机号的运营商以及对应的归属地
 *
 * @Author: lmf
 * @Create: 2025/3/11 22:33
 * @module
 */
@Slf4j
@Service(value = "phase")
public class PhaseStrategyFilter implements StrategyFilter {
    @Autowired
    private BeaconCacheClient cacheClient;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private MobilOperatorUtil mobilOperatorUtil;

    @Override
    public void strategy(StandardSubmit submit) {
        log.info("startTime:{}=========>>>>>>", System.currentTimeMillis());
        log.info("校验phaseStrategyFilter");
        // 手机号未知
        String UNKNOWN = "未知 未知,未知";
        // 手机区域和运营商
        int AREA_OPERATOR_LENGTH = 2;
        // 获取手机号前7位
        int MOBILE_START = 0;
        int MOBILE_END = 7;
        //1、根据手机号前7位，查询手机号信息
        String mobile = submit.getMobile().substring(MOBILE_START, MOBILE_END);
        // 获取redis中通道信息
        String cacheMobileInfo = cacheClient.getString(CacheConstant.PHASE + mobile);

        getMobileInfo:
        if (StringUtils.isEmpty(cacheMobileInfo)) {
            cacheMobileInfo = mobilOperatorUtil.getMobileInfo(mobile);
            if (StringUtils.isNotEmpty(cacheMobileInfo)) {
                log.info("手机号验证mobile check");
                // 数据库中没有但是有的号段放到数据库中去
                rabbitTemplate.convertAndSend(RabbitMQConstants.MOBILE_AREA_SET, submit.getMobile());
                break getMobileInfo;
            }
            cacheMobileInfo = UNKNOWN;
        }
        //2、查询不到，需要调用三方接口，查询手机号对应信息

        //3、调用三方查到信息后，发送消息到MQ，并且同步到MySQL和Redis

        //4、无论是Redis还是三方接口查询到之后，封装到StandardSubmit对象中
        String[] areaAndOperator = cacheMobileInfo.split(mobilOperatorUtil.SEPARATE);
        if (areaAndOperator.length == AREA_OPERATOR_LENGTH) {
            submit.setArea(areaAndOperator[0]);
            submit.setOperatorId(OperatorUtil.getOperatorCode(areaAndOperator[1]));
        }
    }
}
